import { Module, Logger } from '@nestjs/common';
import { MailerModule } from '@nestjs-modules/mailer';
import { ConfigService } from '@nestjs/config';
import { HandlebarsAdapter } from '@nestjs-modules/mailer/dist/adapters/handlebars.adapter';
import { join } from 'path';
import { MailService } from './mail.service';
import * as nodemailer from 'nodemailer';

@Module({
  imports: [
    MailerModule.forRootAsync({
      useFactory: async (configService: ConfigService) => {
        const logger = new Logger('MailModule');
        
        // 获取项目根目录
        const rootDir = process.cwd();
        // 在开发环境使用src目录，生产环境使用dist目录
        const templateDir = process.env.NODE_ENV === 'production'
          ? join(rootDir, 'dist', 'modules', 'mail', 'templates')
          : join(rootDir, 'src', 'modules', 'mail', 'templates');

        // 获取邮件配置
        const mailHost = configService.get<string>('MAIL_HOST');
        const mailPort = configService.get<string>('MAIL_PORT');
        const mailUser = configService.get<string>('MAIL_USER');
        const mailPassword = configService.get<string>('MAIL_PASSWORD');
        const mailFrom = configService.get<string>('MAIL_FROM');
        const mailSecure = configService.get<string>('MAIL_SECURE');

        if (!mailHost || !mailPort || !mailUser || !mailPassword || !mailFrom) {
          throw new Error('Missing required mail configuration');
        }

        // 打印邮件配置信息
        logger.debug('Mail configuration:', {
          host: mailHost,
          port: mailPort,
          secure: mailSecure,
          user: mailUser,
          from: mailFrom,
          templateDir,
        });

        const transport = {
          host: mailHost,
          port: parseInt(mailPort),
          secure: mailSecure === 'true',
          auth: {
            user: mailUser,
            pass: mailPassword,
          },
          tls: {
            ciphers: 'SSLv3',
            rejectUnauthorized: false
          },
          debug: true,
          logger: true
        };

        // 测试邮件连接
        try {
          const testTransport = nodemailer.createTransport(transport);
          await testTransport.verify();
          logger.log('Successfully connected to email server');
        } catch (error) {
          logger.error('Failed to connect to email server:', error);
          throw error;
        }

        return {
          transport,
          defaults: {
            from: `"Monday项目管理系统" <${mailFrom}>`,
          },
          template: {
            dir: templateDir,
            adapter: new HandlebarsAdapter(),
            options: {
              strict: true,
            },
          },
        };
      },
      inject: [ConfigService],
    }),
  ],
  providers: [MailService],
  exports: [MailService],
})
export class MailModule {} 